import { getToken, setToken, removeToken } from '@/utils/storage'
import { login as loginAPi, getUserInfo as getUserInfoAPi } from '@/api/user'
const state = {
  token: getToken(), // 缓存
  userinfo: {}
}
const mutations = {
  updateTpken (state, token) {
    state.token = token
    // 存入本地
    setToken(token)
  },
  delToken (state) {
    state.token = null
    removeToken()
  },
  updateUserinfo (state, payload) {
    state.userinfo = payload
  }
}
const actions = {
  async login (context, data) {
    // 登录请求
    const res = await loginAPi(data)
    context.commit('updateTpken', res)
  },
  async getUserinfo ({ commit }) {
    const res = await getUserInfoAPi()
    commit('updateUserinfo', res)
  },
  // 退出 要清空本地存储 和 vue缓存的用户信息
  logout ({ commit }) {
    commit('delToken')
    commit('updateUserinfo', {})
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
